<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :style="'width:' + width + 'px;height:' + height + 'px;'"
      :action="uploadUrl"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img
        v-if="value"
        :src="value"
        class="avatar"
        :style="'width:' + width + 'px;height:' + height + 'px;'"
      />
      <i
        v-else
        class="el-icon-plus avatar-uploader-icon"
        :style="
          'width:' +
          width +
          'px;height:' +
          height +
          'px;line-height:' +
          height +
          'px;'
        "
      ></i>
    </el-upload>
  </div>
</template>

<script>
import { APP_URL } from "@/libs/config";
export default {
  name: "UploadImage",
  props: {
    // 图片地址
    value: {
      type: String,
      default: "",
    },
    // 上传接口
    uploadUrl: {
      type: String,
      default: "http://localhost:3000/api/v1/upload/img",
    },
    width: {
      type: Number,
      default: 100,
    },
    height: {
      type: Number,
      default: 100,
    },
  },
  methods: {
    handleAvatarSuccess(res, file) {
      let imageUrl = APP_URL + res.src;
      //   父组件v-model绑定后自动监听
      this.$emit("input", imageUrl);
    },
    handleAvatarError(err, file, fileList) {
      // 监听错误
      this.$emit("error", err);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang='scss' scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
.avatar {
  display: block;
}
</style>
